import matplotlib.pyplot as plt
import numpy as np
import sympy as sp


def set_chinese_font():
    """设置中文字体"""
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

set_chinese_font()

def sequences_and_series():
    print("=== 数列与级数 ===")
    
    # 等差数列
    def arithmetic_sequence(a1, d, n):
        return [a1 + i * d for i in range(n)]
    
    # 等比数列
    def geometric_sequence(a1, r, n):
        return [a1 * (r ** i) for i in range(n)]
    
    # 斐波那契数列
    def fibonacci_sequence(n):
        fib = [0, 1]
        for i in range(2, n):
            fib.append(fib[i-1] + fib[i-2])
        return fib[:n]
    
    # 示例
    arith_seq = arithmetic_sequence(2, 3, 10)
    geo_seq = geometric_sequence(2, 3, 10)
    fib_seq = fibonacci_sequence(15)
    
    print(f"等差数列 (首项2, 公差3): {arith_seq}")
    print(f"等比数列 (首项2, 公比3): {geo_seq}")
    print(f"斐波那契数列: {fib_seq}")
    
    # 数列求和
    arith_sum = sum(arith_seq)
    geo_sum = sum(geo_seq)
    
    print(f"\n等差数列和: {arith_sum}")
    print(f"等比数列和: {geo_sum}")
    
    # 数列极限
    def sequence_limit(sequence_func, n_terms=1000):
        terms = [sequence_func(n) for n in range(1, n_terms + 1)]
        return terms[-1]
    
    # 示例: 1/n 的极限
    limit_seq = sequence_limit(lambda n: 1/n)
    print(f"数列 1/n 的极限近似值: {limit_seq}")
    
    # 可视化数列
    plt.figure(figsize=(12, 4))
    
    plt.subplot(1, 3, 1)
    plt.plot(range(1, 11), arith_seq, 'bo-')
    plt.title('等差数列')
    plt.grid(True)
    
    plt.subplot(1, 3, 2)
    plt.plot(range(1, 11), geo_seq, 'ro-')
    plt.title('等比数列')
    plt.grid(True)
    
    plt.subplot(1, 3, 3)
    plt.plot(range(1, 16), fib_seq, 'go-')
    plt.title('斐波那契数列')
    plt.grid(True)
    
    plt.tight_layout()
    plt.show()

sequences_and_series()